<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>登录页面</title>
    <!-- <script src="../lib/jquery-1.12.4.min.js"></script> -->
</head>

<body>
    <form action="">
        <label>用户名：</label>
        <input type="text" id="username" name="username" /><br />
        <label>密码：</label>
        <input type="password" id="password" name="password" /><br />
        <button>登录</button>
    </form>

    <script>
        document.querySelector("form").onsubmit = function(e) {
            e.preventDefault();

            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            var xhr = new XMLHttpRequest();
            // console.log(xhr);
            xhr.onload = function() {
                var res = JSON.parse(this.responseText);
                // console.log(res); // {status: 200, msg: "登录成功"}
                alert(res.msg);
                if (res.status === 200) {
                    location.href = "/index.html";
                }
            };
            xhr.open("POST", "/api/login");
            xhr.setRequestHeader(
                "Content-Type",
                "application/x-www-form-urlencoded"
            );
            xhr.send("username=" + username + "&password=" + password);
        };

        // $(function() {
        //     $("form").on("submit", function(e) {
        //         e.preventDefault();

        //         $.ajax({
        //             type: "POST",
        //             url: "/api/login",
        //             // data: data,
        //             success: function(res) {
        //                 console.log(res);
        //             },
        //         });
        //     });
        // });
    </script>
</body>

</html>